package org.example.yulinwumei;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.example.Main;
import org.example.SalesClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

public class WuMei_XiaoShou {
    private static final Logger logger = LoggerFactory.getLogger(WuMei_XiaoShou.class);
    private static String mdate;
    /**
     * 主方法，用于执行整个程序流程。
     *
     */
    public boolean execute (LocalDate date) {
        mdate = date.toString();
        try {
            // 第一步：获取登录 Cookie
            Map<String, String> cookies = loginAndGetCookies();
            // 第二步：携带 Cookie 发送数据请求
            JSONArray data = fetchDataWithCookies(cookies);
            // 第三步
            if (data != null && !data.isEmpty()){
                //上传数据
                return SalesClient.postRequest(data, "榆林物美", date.toString());
            }
            logger.info("榆林物美未获取到" + date.toString() + "有效数据");
            return false;

        } catch (Exception e) {
            logger.error("物美登录：发生异常 ", e);
            return false;
        }
    }
    /**
     * 将日期字符串从一种格式转换为另一种格式。
     *
     * @param inputDate 输入的日期字符串，格式为"yyyy-MM-dd"
     * @return 转换后的日期字符串，格式为"MMM d yyyy"，如"Jan 1 2023"
     * @throws RuntimeException 如果输入的日期字符串不符合预期格式，则抛出此异常
     */
    public static String dateToSting(String inputDate){
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = inputFormat.parse(inputDate);
            SimpleDateFormat outputFormat = new SimpleDateFormat("MMM d yyyy", Locale.ENGLISH);
            return outputFormat.format(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录并获取Cookies
     *
     * @return 登录成功后返回的Cookies，Map的键为Cookie的名称，值为Cookie的值
     * @throws Exception 登录过程中可能出现的异常
     */
    private static Map<String, String> loginAndGetCookies() throws Exception {
        String postUrl = "https://vc.wumart.com/doLogin";
        String postParams = "mandt=307&accountOrtelephone=%E5%AE%81%E5%A4%8F%E6%96%B0%E5%A4%A9%E7%84%B6%E5%95%86%E8%B4%B8%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&pwd=Xtr262894%40";

        HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0");

        try (OutputStream os = conn.getOutputStream()) {
            os.write(postParams.getBytes(StandardCharsets.UTF_8));
        }

        return parseCookies(conn.getHeaderFields().get("Set-Cookie"));
    }

    /**
     * 使用Cookies获取数据
     *
     * @param cookies Cookies的键值对集合
     * @return 获取到的数据字符串
     * @throws Exception 当连接失败或读取响应时发生异常
     */
    private static JSONArray fetchDataWithCookies(Map<String, String> cookies) throws Exception {
        String apiUrl = "https://rebate-partner.wumart.com/vc/joinReport/detailList?_menu=%23full%2Frebate%2Fvc%2Fjoint%2Fsale";

        // 构建 POST 数据
        String formData = "groupBy=" + URLEncoder.encode("supplier_code", "UTF-8") +
                "&groupBy=" + URLEncoder.encode("shop_code", "UTF-8") +
                "&groupBy=" + URLEncoder.encode("goods_code", "UTF-8") +
                "&groupBy=" + URLEncoder.encode("sale_date", "UTF-8") +
                "&perPageSize=200" +
                "&bizRange=" + URLEncoder.encode(dateToSting(mdate), "UTF-8") +
                "&bizRange=" + URLEncoder.encode(dateToSting(mdate), "UTF-8") +
                "&pageNo=1";

        HttpURLConnection conn = (HttpURLConnection) new URL(apiUrl).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0");
        conn.setRequestProperty("Origin", "https://vc.wumart.com");
        conn.setRequestProperty("Referer", "https://vc.wumart.com/");
        conn.setRequestProperty("Cookie", buildCookieString(cookies));

        try (OutputStream os = conn.getOutputStream()) {
            os.write(formData.getBytes(StandardCharsets.UTF_8));
        }

        // 读取响应
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            return respinseToJsonArray(response.toString());
        }
    }
    private static JSONArray respinseToJsonArray(String response){
        try {
            ObjectMapper mapper  = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(response);
            ArrayNode jsonArr = (ArrayNode) rootNode.path("data").path("list");
            ArrayNode resultArray = mapper.createArrayNode();
            for (JsonNode node : jsonArr) {
                ObjectNode newNode = mapper.createObjectNode();
                // 映射字段
                newNode.put("条码", node.path("supplierCode").asText());
                newNode.put("名称", node.path("goodsName").asText());
                newNode.put("单价", ""); // 单价留空
                newNode.put("数量", ""); // 数量留空
                newNode.put("金额", node.path("saleAmountTaxedReal").asDouble());
                newNode.put("店名", node.path("shopName").asText());
                newNode.put("区域", "榆林"); // 固定值
                newNode.put("销售时间", node.path("date").asText() + " 00:00:00");
                resultArray.add(newNode);
            }

            // 将 ArrayNode 转换为 JSON 字符串
            String jsonStr = mapper.writeValueAsString(resultArray);
            // 通过字符串构建 org.json.JSONArray
            return new JSONArray(jsonStr);

        } catch (Exception e){
            logger.error("物美获取数据：发生异常 ", e);
            return new JSONArray();
        }
    }


    /**
     * 构建Cookie字符串
     *
     * @param cookies 包含Cookie键值对的Map
     * @return 构建的Cookie字符串
     */
    private static String buildCookieString(Map<String, String> cookies) {
        StringBuilder sb = new StringBuilder();
        cookies.forEach((k, v) -> {
            if (sb.length() > 0) sb.append("; ");
            sb.append(k).append("=").append(v);
        });
        return sb.toString();
    }

    /**
     * 将Cookie头信息解析为键值对形式的Map
     *
     * @param cookieHeaders Cookie头信息列表
     * @return 包含解析后Cookie的Map，键为Cookie名，值为Cookie值
     */
    private static Map<String, String> parseCookies(List<String> cookieHeaders) {
        Map<String, String> cookieMap = new HashMap<>();
        if (cookieHeaders == null) return cookieMap;

        for (String header : cookieHeaders) {
            String[] parts = header.split(";", 2)[0].split("=", 2);
            if (parts.length == 2) {
                cookieMap.put(parts[0].trim(), parts[1].trim());
            }
        }
        return cookieMap;
    }
}